package com.project.dao.impl;

import com.project.bean.CutPageBean;
import com.project.bean.ProductBean;
import com.project.dao.IProductDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;

@Repository
public class ProductImpl extends BaseDao implements IProductDao {
    @Override
    public CutPageBean<ProductBean> findByItem(int pageNO, String name) {
        CutPageBean<ProductBean> cutBean = new CutPageBean<>();
        String sql = "SELECT  p.*,COUNT(s.`pk_speakId`) speakNum FROM t_product p LEFT JOIN t_speak s ON p.`pk_productId`=s.`fk_productId`";
        String dynaSql = " WHERE 1=1 ";
        if (name != null && name.length() != 0) {
            dynaSql += "and p_name like '%" + name + "%' ";
        }

        this.setConnection();
        try {
            ps = con.prepareStatement(sql + dynaSql + " GROUP BY p.`pk_productId` LIMIT ?,? ");
            ps.setObject(1, (pageNO - 1) * CutPageBean.PAGESIZE);
            ps.setObject(2, CutPageBean.PAGESIZE);

            rs = ps.executeQuery();
            while (rs.next()) {
                cutBean.getList().add(this.getProduct());
            }


            ps = con.prepareStatement("select count(*) c from t_product " + dynaSql);
            rs = ps.executeQuery();

            if (rs.next()) {
                cutBean.setCount(rs.getInt("c"));
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            this.closeConnection();
        }


        return cutBean;
    }

    @Override
    public ProductBean findById(Integer id) {
        ProductBean product = null;

        this.setConnection();
        try {
            ps = con.prepareStatement("select p.*,count(s.`pk_speakId`) speakNum from t_product p left join t_speak s on p.`pk_productId`=s.`fk_productId` where p.pk_productId = ?");
            ps.setObject(1,id);
            rs=ps.executeQuery();
            if (rs.next()){
                product=this.getProduct();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeConnection();
        }

        return product;
    }

    private ProductBean getProduct() {
        ProductBean product = new ProductBean();
        try {
            product.setId(rs.getInt("pk_productId"));
            product.setName(rs.getString("p_name"));
            product.setPrice(rs.getInt("p_price"));
            product.setImgPath(rs.getString("p_imgPath"));
            product.setSpeakNum(rs.getInt("speakNum"));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return product;
    }
}
